package org.jparrow.framework.helper;

import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.jparrow.framework.util.CollectionUtil;
import org.jparrow.framework.util.PropsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 
 * @author supda
 * @Date 2017-3-24 ����3:10:42
 *
 * ��ݿ����������
 * 	1.����commons-dbutils���ص�PreparedStatement��ResultSet
 *  2.����ThreadLocal������Session�����û�����룩��Connection�����ص�Connection��
 *  	������رա���ȷ��һ���û�ֻ�����һ��Connection��
 *  
 *  3.δ�ܽ����������Connection�����⡣������ݿ����ӳأ�common-dbcp
 *  
 *  commons-dbutils��
 *  1.BeanHandler---����bean����
 *  2.BeanListHandler---����list����
 *  3.BeanMapHandler---����map����
 *  4.ArrayHandler---����Object[]����
 *  5.ArrayListHandler---����List����
 *  6.MapHandler---����Map����
 * 	 7.MapListHandler---List<>����
 *   8.ScalarHandler---����ĳ�е�ֵ
 *   9.ColumnListHandler---����ĳ�е�ֵ�б�
 *   10.KeyedHandler---����Map<>������Ҫָ������
 */
public final class DataBaseHelper {

	private static final Logger LOGGER = 
			LoggerFactory.getLogger(DataBaseHelper.class);
	
	//�̳߳��е�Connection
	private static final ThreadLocal<Connection> CONNECTION_HOLDER;
	
	//dbutils��ѯ�ӿ�
	private static final QueryRunner QUERY_RUNNER;
	
	//��ݿ����ӳ�����������
	private static final ComboPooledDataSource  DATA_SOURCE;
	
	static{
		
		CONNECTION_HOLDER=
				new ThreadLocal<Connection>();
		
		QUERY_RUNNER = 
				new QueryRunner();
		
		Properties conf = PropsUtil.loadProps("config.properties");
		
		String driver = conf.getProperty("jdbc.driver");
		String url = conf.getProperty("jdbc.url");
		String username = conf.getProperty("jdbc.username");
		String password = conf.getProperty("jdbc.password");
		
		DATA_SOURCE = new ComboPooledDataSource();
		try {
			DATA_SOURCE.setDriverClass(driver);
		} catch (PropertyVetoException e) {
			LOGGER.error("can not load sql driver:", e);
		}
		DATA_SOURCE.setJdbcUrl(url);
		DATA_SOURCE.setUser(username);
		DATA_SOURCE.setPassword(password);
	}
	

	
	/**
	 * ��ѯʵ���б�
	 */
	public static <T> List<T> queryEntityList(Connection conn, Class<T> entityClass, 
			String sql, Object ...params){
		List<T> entityList;
		try{
			entityList = QUERY_RUNNER.query(
					conn, sql,new BeanListHandler<T>(entityClass), params);
			
		}catch (SQLException e) {
			LOGGER.error("query entity list failure", e);
			throw new RuntimeException(e);
		}finally{
			//���رգ�ThreadLocalά�����ӣ��´���ݿ����ʹ��
		}
		
		return entityList;
	}
	
	/**
	 * ��ѯʵ���б�
	 */
	public static <T> List<T> queryEntityList( Class<T> entityClass, 
			String sql, Object ...params){
		List<T> entityList;
		try{
			entityList = QUERY_RUNNER.query(
					getConnection(), sql,new BeanListHandler<T>(entityClass), params);
			
		}catch (SQLException e) {
			LOGGER.error("query entity list failure", e);
			throw new RuntimeException(e);
		}finally{
			//���رգ�ThreadLocalά�����ӣ��´���ݿ����ʹ��
		}
		
		return entityList;
	}
	
	
	/**
	 * ��ѯʵ���б�
	 */
	public static <T> List<T> queryEntityList(Connection conn, Class<T> entityClass, 
			String sql){
		List<T> entityList;
		try{
			entityList = QUERY_RUNNER.query(
					conn, sql,new BeanListHandler<T>(entityClass));
			
		}catch (SQLException e) {
			LOGGER.error("query entity list failure", e);
			throw new RuntimeException(e);
		}finally{
			//���رգ�ThreadLocalά�����ӣ��´���ݿ����ʹ��
		}
		
		return entityList;
	}
	
	
	/**
	 * ��ѯʵ���б�
	 */
	public static <T> List<T> queryEntityList( Class<T> entityClass, 
			String sql){
		List<T> entityList;
		try{
			entityList = QUERY_RUNNER.query(
					getConnection(), sql,new BeanListHandler<T>(entityClass));
			
		}catch (SQLException e) {
			LOGGER.error("query entity list failure", e);
			throw new RuntimeException(e);
		}finally{
			//���رգ�ThreadLocalά�����ӣ��´���ݿ����ʹ��
		}
		
		return entityList;
	}
	
	
	/**
	 * ��ѯʵ��
	 */
	public static <T> T queryEntity(Class<T> entityClass, 
			String sql, Object...params){
		T entity;
		try{
			entity = QUERY_RUNNER.query(
					getConnection(),sql,new BeanHandler<T>(entityClass),params);
			
		}catch (SQLException e) {
			LOGGER.error("query entity list failure", e);
			throw new RuntimeException(e);
		}finally{
			//���رգ�ThreadLocalά�����ӣ��´���ݿ����ʹ��
		}
		
		return entity;
	}
	
	/**
	 * ִ�в�ѯ���
	 */
	public static List<Map<String, Object>> execteQuery(String sql, Object ...params){
		List<Map<String, Object>> result;
		
		try{
			result = QUERY_RUNNER.query(
					getConnection(), sql, new MapListHandler(), params);
		}catch(Exception e){
			LOGGER.error("execute query failure", e);
			throw new RuntimeException(e);
		}finally{
			//���رգ�ThreadLocalά�����ӣ��´���ݿ����ʹ��
		}
		return result;
	}
	
	/**
	 * ִ�и������(����update��insert��delete)
	 */
	public static int executeUpdate(String sql, Object ...params){
		int rows = 0;
		try{
			rows = QUERY_RUNNER.update(getConnection(), sql, params); 
		}catch(SQLException e){
			LOGGER.error("execute update failure", e);
			throw new RuntimeException(e);
		}finally{
			closeConnection();
		}
		return rows;
	}
	

	public static int execteUpdate(String sql) {
		return executeUpdate(sql,null);
	}
	
	
	/**
	 * ����ʵ��
	 */
	public static <T> boolean insertEntity(Class<T> entityClass, 
			Map<String , Object> fieldMap){
		if(CollectionUtil.isEmpty(fieldMap)){
			LOGGER.error("can not insert entity: fieldMap is empty");
			return false;
		}
		
		String sql = "INSERT INTO " + getTableName(entityClass);
		StringBuilder columns = new StringBuilder("(");
		StringBuilder values = new StringBuilder("(");
		
		for(String fieldName : fieldMap.keySet()){
			columns.append(fieldName).append(", ");
			values.append("?, ");
		}

		columns.replace(columns.lastIndexOf(", "), columns.length(), ")");
		values.replace(values.lastIndexOf(", "), values.length(), ")");
		
		sql += columns + " VALUES "+ values;
		
		//Map��valueת����
		Object[] params = fieldMap.values().toArray();
		
		return executeUpdate(sql, params) == 1;
	}
	
	/**
	 * ����ʵ��
	 */
	public static <T> boolean updateEntity(Class<T> entityClass, long id 
			,Map<String, Object> fieldMap){
		
		if(CollectionUtil.isEmpty(fieldMap)){
			LOGGER.error("can not update entity: fieldMap is empty");
			return false;
		}
		
		String sql = "UPDATE "+ getTableName(entityClass) +" SET ";
		StringBuilder columns = new StringBuilder();
		for(String fieldName : fieldMap.keySet()){
			columns.append(fieldName).append("=?, ");
		}
		sql += columns.substring(0, columns.lastIndexOf(", "))+" WHERE id = ?";
		
		List<Object> paramList = new ArrayList<Object>();
		paramList.addAll(fieldMap.values());
		paramList.add(id);
		
		Object[] params = paramList.toArray();
		
		return executeUpdate(sql, params) == 1;
	}
	
	/**
	 * ɾ��ʵ��
	 */
	public static <T> boolean deleteEntity(Class<T> entityClass, long id){
		String sql = "DELETE FROM "+ getTableName(entityClass) + " WHERE id=?";
		return executeUpdate(sql, id) == 1;
	}
	
	/**
	 * ��ȡ����
	 */
	private static String getTableName(Class<?> entityClass){
		return entityClass.getSimpleName();
	}
	
	/**
	 * ��ȡ��ݿ�����
	 */
	public static Connection getConnection(){
		//�˴��ǻ�ȡ�ĵ�ǰ�̵߳�Connection
		Connection conn = CONNECTION_HOLDER.get();
		
		if(conn == null){
			try{
				conn = DATA_SOURCE.getConnection();
			}catch (SQLException e) {
				LOGGER.error("get connection failure", e);
				throw new RuntimeException(e);
			}finally{
				CONNECTION_HOLDER.set(conn);
			}
		}
		
		return conn;
	}
	
	/**
	 * �ر���ݿ�����
	 */
	public static void closeConnection(){
		Connection connection = CONNECTION_HOLDER.get();
		if(connection != null){
			try{
				connection.close();
			}catch (SQLException e) {
				LOGGER.error("close jdbc connection failure", e);
				throw new RuntimeException(e);
			}finally{
				CONNECTION_HOLDER.remove();
			}
		}
	}

	/**
	 * ִ��sql �ļ�
	 */
	public static void executeSqlFile(String filepath){
		InputStream is = Thread.currentThread().
				getContextClassLoader().getResourceAsStream(filepath);
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String sql;
		try{
			while((sql = reader.readLine()) != null){
				DataBaseHelper.execteUpdate(sql);
			}
		}catch(Exception e){
			LOGGER.error("execute sql file failure ", e);
			throw new RuntimeException(e);
		}
	}
	
}
